package apibasej.db.server.utilmetadata;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import apibasej.db.metadata.Col;
import apibasej.db.metadata.Tab;

public class UtilDatabaseMetadata {

	
	public static boolean existsTable(DatabaseMetaData dmd, String tableNamePattern) throws SQLException{
		try(ResultSet rs = dmd.getTables(null, null, tableNamePattern, null)){ //dmd.getTables(null, null, "%", null)
			return rs.next();
		}
	}
	
	
	//replaceClass: usado se quise substituir algum tipo de coluna
	//indirectForeignCols: para indicar as colunas que são uma fk que aponta para uma tabela intermediária, e não uma tabela direta de destino
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void createColsInEmptyTab(Tab emptyTab, Connection conn, HashMap<Class<?>,Class<?>> replaceClass, ArrayList<String> indirectForeignCols, ArrayList<String> colsToIgn) throws SQLException, ClassNotFoundException{
		
		ResultSet rsAux = conn.prepareStatement("SELECT * FROM "+emptyTab.getNameForSql()+" WHERE 1=0 ").executeQuery();//dmd.getColumns(null, "public", tabName, null);
		ResultSetMetaData rsmd = rsAux.getMetaData();
		for(int i=1;i<=rsmd.getColumnCount();i++){
			String name = rsmd.getColumnName(i);
			String className = rsmd.getColumnClassName(i);
			Class<?> classCol = Class.forName(className);
			if(replaceClass!=null && replaceClass.containsKey(classCol)) {
				classCol = replaceClass.get(classCol);
			}
			int displaySize = rsmd.getColumnDisplaySize(i);// qtd caracteres exibição
			int precision = rsmd.getPrecision(i);
			int scale = rsmd.getScale(i);
			int type = rsmd.getColumnType(i);
			String typeName = rsmd.getColumnTypeName(i);
			boolean notNull = rsmd.isNullable(i)==0;
			boolean signed = rsmd.isSigned(i);
			
			String nameColWithTab = emptyTab.getName()+"."+name;
			boolean isIndirectForeignCol = indirectForeignCols!=null && indirectForeignCols.contains(nameColWithTab);
			
			if(colsToIgn!=null && colsToIgn.contains(nameColWithTab)){
				System.out.println("COLUNA IGNORADA: "+nameColWithTab);
				continue;
			}
			
			//ao criar a col já adiciona na tab pai
			new Col(emptyTab, name, classCol, displaySize, precision, scale, type, typeName, notNull, signed, null, null, isIndirectForeignCol);
		}
		
	}
	
}
